package com.github.bridge.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.dtflys.forest.exceptions.ForestHandlerException;
import com.github.bridge.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Object exception(HttpServletResponse response, Exception e) {
        log.error("An unexpected error occurred: ", e);
        int status = HttpStatus.OK.value();
        response.setStatus(status);
        return R.build(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }

    @ExceptionHandler(value = ForestHandlerException.class)
    public Object forestHandlerException(HttpServletResponse response, Exception e) {
        log.error("ForestConvertException:{}", e.getMessage());
        int status = HttpStatus.OK.value();
        response.setStatus(status);
        return R.build(HttpStatus.INTERNAL_SERVER_ERROR.value(), "异常");
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object methodArgumentNotValidException(HttpServletResponse response, Exception e) {
        log.error("参数异常验证", e);
        int status = HttpStatus.BAD_REQUEST.value();
        response.setStatus(status);
        MethodArgumentNotValidException ex = (MethodArgumentNotValidException)e;
        return R.build(status, Objects.requireNonNull(ex.getBindingResult().getFieldError()).getDefaultMessage());
    }

    @ExceptionHandler(value = NotLoginException.class)
    public Object notLoginException(HttpServletResponse response, Exception e) {
        log.error("异常", e);
        NotLoginException ex = (NotLoginException) e;
        String type = ex.getType();
        if (NotLoginException.NOT_TOKEN.equals(type)) {
            return R.build(500, "token不存在");
        } else if (NotLoginException.INVALID_TOKEN.equals(type)) {
            return R.build(500, "token无效");
        } else if (NotLoginException.TOKEN_TIMEOUT.equals(type)) {
            return R.build(500, "token过期");
        }
        return R.build(500, ex.getMessage());
    }

    @ExceptionHandler(value = CustomException.class)
    public Object customException(HttpServletResponse response, Exception e) {
        CustomException ex = (CustomException) e;
        Integer code = ex.getCode();
        String message = ex.getMessage();
        int status = HttpStatus.OK.value();
        response.setStatus(status);
        return R.build(code, message);
    }


}
